import React, { useState } from 'react';
import { Table, Tag, Space, Button, } from 'antd';
import { connect } from 'umi'
import UserModal from './components/UserModal'

const Users = (props: any) => {
    const { users, dispatch } = props;
    console.log(props);

    const [isModalVisible, setIsModalVisible] = useState(false);
    const [formValues, setFormValues] = useState<any>({});


    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            render: (text: any) => <a>{text}</a>,
        },
        {
            title: 'email',
            dataIndex: 'email',
            key: 'email',
        },
        {
            title: 'create_time',
            dataIndex: 'create_time',
            key: 'create_time',
        },
        {
            title: 'update_time',
            dataIndex: 'update_time',
            key: 'update_time',
        },

        {
            title: 'Action',
            key: 'action',
            render: (text: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => onEdit(record)}>编辑 {record.name}</a>
                    <a>删除</a>
                </Space>
            ),
        },
    ];

    const onEdit = (val: any) => {
        setIsModalVisible(true);
        val.status === 0 ? true : false;
        setFormValues(val);
    }
    const onFinish = (val: any) => {

        let id = 0;
        if (formValues) {
            id = formValues.id;
        }
        if (id) {
            dispatch({
                type: 'users/edit',
                payload: {
                    id,
                    val,
                }
            });
        } else {

            dispatch({
                type: 'users/add',
                payload: {
                    val
                }
            });
        }

        setIsModalVisible(false);
    }

    const openModal = () => {
        setIsModalVisible(true)
        setFormValues(undefined);
    }


    return (
        <div>
            <Space style={{ width: '100%' }} direction="vertical">
                <Button type="primary" onClick={openModal}>新增</Button>
                <Table rowKey={record => record.id} columns={columns} dataSource={users.data} />
            </Space>
            <UserModal onFinish={onFinish} formValues={formValues} ModalVisible={{ isModalVisible, setIsModalVisible }} />
        </div>
    )
};
//与reduce连接
const mapStateToProps = ({ users }) => ({
    users,
})
export default connect(mapStateToProps)(Users);